import http from "@/api/request.js";
import axios from "axios";

// 存储 AbortController 实例
let abortController = null;

// 取消请求
export const cancelRequest = () => {
  if (abortController) {
    abortController.abort();
    console.log("请求已被用户取消");
    abortController = null;
  }
};

export const ddq = async () => {
  try {
    // 取消之前的请求
    cancelRequest();

    // 创建新的 AbortController
    abortController = new AbortController();

    const response = await http({
      url: "/posts",
      method: "get",
      signal: abortController.signal, // 使用 signal 替代 cancelToken
    });

    // 模拟前端延迟（注意：这不会触发 cancel）
    await new Promise(resolve => setTimeout(resolve, 10000));

    // 成功后清理
    abortController = null;

    return response.data;
  } catch (error) {
    if (error.name === "CanceledError" || error.name === "AbortError") {
      console.log("请求被取消:", error.message);
    } else {
      console.error("请求出错:", error);
    }
    abortController = null;
    throw error;
  }
};
